package com.bawei.module_message.ui

import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context.NOTIFICATION_SERVICE
import android.media.RingtoneManager
import android.net.Uri
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat.getSystemService
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.bawei.lib_common.base.BaseFragment
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Empty
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_common.observeWithLifecycle
import com.bawei.lib_common.utils.ToastUtils
import com.bawei.lib_storage.AppMMKV
import com.bawei.module_message.R
import com.bawei.module_message.adapter.MessageAdapter
import com.bawei.module_message.databinding.FragmentMessageBinding
import com.bawei.module_message.http.MessageViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class MessageFragment : BaseFragment<BaseViewModel,FragmentMessageBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_message

    private val messageViewModel:MessageViewModel by viewModels()
    var userId=0
    private val messageAdapter:MessageAdapter  by lazy {
        MessageAdapter()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        super.initView()
        userId=AppMMKV.userId

        initAdapter()
        initNotificationSettings()

        // 2. 总开关联动逻辑
        mBinding.switch1.setOnCheckedChangeListener { _, isChecked ->
            // 启用/禁用子开关
//            mBinding.layoutSound.alpha = if (isChecked) 1f else 0.5f
            mBinding.switch2.isEnabled = isChecked
            if (!isChecked){
                mBinding.switch2.isChecked = false
            }
//            mBinding.layoutVibration.alpha = if (isChecked) 1f else 0.5f
            mBinding.switch3.isEnabled = isChecked
            if (!isChecked){
                mBinding.switch3.isChecked = false
            }

            // 同步系统通知权限
            if (isChecked) {
                requestNotificationPermission()
            } else {
                disableSystemNotifications()
            }
        }

        // 3. 声音开关监听
        mBinding.switch2.setOnCheckedChangeListener { _, isChecked ->
            setSystemNotificationSound(isChecked)
        }

        // 4. 震动开关监听
        mBinding.switch3.setOnCheckedChangeListener { _, isChecked ->
            setSystemNotificationVibration(isChecked)
        }
    }

    override fun initData() {
        messageViewModel.getMessage("89c13df9ef6f48a5ae7cf382c120daff",userId)
    }

    override fun initListener() {
        messageViewModel.messageState.observeWithLifecycle(this){
            when(it){
                Empty -> {}
                is Failed ->{}
                Loading -> {}
                Success -> {
                    messageAdapter.setData(messageViewModel.messageList)
                }
            }
        }
    }

    fun initAdapter(){
        mBinding.messagerv1.layoutManager=LinearLayoutManager(context)
        mBinding.messagerv1.adapter=messageAdapter
    }
    @RequiresApi(Build.VERSION_CODES.O)
    private fun initNotificationSettings() {
        // 读取系统通知设置（需适配不同Android版本）
        val areNotificationsEnabled = NotificationManagerCompat.from(requireActivity()).areNotificationsEnabled()
        mBinding.switch1.isChecked = areNotificationsEnabled

        if (areNotificationsEnabled) {
            // 读取声音和震动设置（需使用NotificationChannel API）
            val channel = getSystemNotificationChannel()
            mBinding.switch2.isChecked = channel.sound != null
            mBinding.switch3.isChecked = channel.shouldVibrate()
        }
    }
    private fun requestNotificationPermission() {
        // Android 13+ 需要动态请求通知权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestPermissions(
                arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),
                REQUEST_CODE_NOTIFICATION
            )
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun disableSystemNotifications() {
        // 关闭系统通知
        NotificationManagerCompat.from(requireActivity()).cancelAll()

        // 实际项目中应禁用通知渠道
        val channel = getSystemNotificationChannel()
        channel.apply {
            importance = NotificationManager.IMPORTANCE_NONE
            setSound(null, null)
            enableVibration(false)
        }
        (requireActivity().getSystemService(NOTIFICATION_SERVICE) as NotificationManager)
            .createNotificationChannel(channel)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setSystemNotificationSound(enable: Boolean) {
        val channel = getSystemNotificationChannel()
        channel.apply {
            if (enable) {
                setSound(
                    Uri.parse("${RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)}"),
                    null
                )
            } else {
                null
            }
        }
        updateNotificationChannel(channel)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setSystemNotificationVibration(enable: Boolean) {
        val channel = getSystemNotificationChannel()
        channel.enableVibration(enable)
        updateNotificationChannel(channel)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun getSystemNotificationChannel(): NotificationChannel {
        // 获取或创建通知渠道（Android 8.0+）
        val manager = requireActivity().getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        return manager.getNotificationChannel(CHANNEL_ID) ?: NotificationChannel(
            CHANNEL_ID,
            "App Notifications",
            NotificationManager.IMPORTANCE_DEFAULT
        ).apply {
            description = "General notifications"
        }
    }
    @RequiresApi(Build.VERSION_CODES.O)
    private fun updateNotificationChannel(channel: NotificationChannel) {
        val manager = requireActivity().getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        manager.createNotificationChannel(channel)
    }


    companion object {
        private const val CHANNEL_ID = "default_channel"
        private const val REQUEST_CODE_NOTIFICATION = 100
    }
}